<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册</title>
    <link rel="icon" href="/img/favicon.png" type="image/png">
    <script src="libs/axios.min.js"></script>
    <script src="libs/vue.global.js"></script>
    <script src="libs/index.full.js"></script>
    <link rel="stylesheet" href="libs/index.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-image: url("img/登录背景图.jpg");
            background-size: cover;
            margin: 0;
        }

        .login-container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            width: 400px;
            text-align: center;
        }

        .bottom-button {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 50px;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="login-container">
            <h2>注册</h2>
            <el-form class="form-container" :model="form" :rules="rules" ref="registerForm" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="form.nickname" placeholder="请输入昵称"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="form.gender">
                        <el-radio label="男">男</el-radio>
                        <el-radio label="女">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="验证码" prop="captcha">
                    <el-input v-model="form.captcha" placeholder="请输入验证码" style="width: 60%;"></el-input>
                    <canvas id="captchaCanvas" width="100" height="40" @click="generateCaptcha"></canvas>
                </el-form-item>
                <el-form-item>
                    <div class="bottom-button">
                        <el-button type="primary" @click="login">登录</el-button>
                        <el-button type="primary" @click="submitForm">注册</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </div>
    </div>

    <script>
        const { createApp } = Vue;
        const { ElMessage } = ElementPlus;
        createApp({
            data() {
                return {
                    form: {
                        username: '',
                        nickname: '',
                        email: '',
                        phone: '',
                        password: '',
                        gender: '',
                        captcha: '',
                    },
                    rules: {
                        username: [{ required: true, message: '请输入用户名', trigger: 'blur' },
                            // { pattern: /^(?=.*[A-Za-z])(?=.*\d).+$/, message: '用户名必须包含字母和数字', trigger: 'blur' }
                        ],
                        nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
                        email: [
                            { required: true, message: '请输入邮箱', trigger: 'blur' },
                            { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
                        ],
                        phone: [
                            { required: true, message: '请输入手机号', trigger: 'blur' },
                            { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
                        ],
                        password: [
                            { required: true, message: '请输入密码', trigger: 'blur' },
                            { min: 6, message: '密码长度至少6位', trigger: 'blur' }
                        ],
                        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
                        captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
                    },
                    generatedCaptcha: ''
                };
            },
            mounted() {
                this.generateCaptcha(); // 初始化验证码
            },
            methods: {
                //格式化时间
                getFormattedTime() {
                    const now = new Date();
                    const year = now.getFullYear();
                    const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从 0 开始，需要 +1
                    const day = String(now.getDate()).padStart(2, "0");
                    const hours = String(now.getHours()).padStart(2, "0");
                    const minutes = String(now.getMinutes()).padStart(2, "0");
                    const seconds = String(now.getSeconds()).padStart(2, "0");
                    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                },
                // 提交表单
                submitForm() {
                    this.$refs.registerForm.validate((valid) => {
                        if (valid) {
                            if (this.form.captcha.toUpperCase() === this.generatedCaptcha) {
                                const currentTime = this.getFormattedTime(); // 获取格式化时间

                                // 构造用户数据
                                const userData = {
                                    username: this.form.username, // 用户名
                                    password: this.form.password, // 密码
                                    email: this.form.email, // 邮箱
                                    phone: this.form.phone, // 手机
                                    nickname: this.form.nickname, // 昵称
                                    sex: this.form.gender, // 性别
                                    status: "ACTIVE", // 状态
                                    role: "USER", // 角色
                                    permissionLevel: 2, // 权限等级
                                    createdTime: currentTime, // 创建时间
                                    updatedTime: currentTime, // 更新时间
                                    lastLoginTime: currentTime // 最近登录时间
                                };

                                // 发送注册请求
                                axios.post("http://localhost:8080/user/register", userData)
                                    .then(response => {
                                        if (response.data.code===200) {
                                            ElMessage.success(response.data.message);
                                            axios.post("http://localhost:8080/visitLog/record")
                                                .then(response => {
                                                    if (response.data.code === 200) {

                                                    } else {
                                                        ElMessage.error(response.data.message || "失败！");
                                                    }
                                                })
                                                .catch(error => {
                                                    ElMessage.error("服务器错误，请稍后再试！");
                                                });
                                            setTimeout(() => {
                                                window.location.href = "/index.html?noticeVisible=true"; // 跳转到主页
                                            }, 1500);
                                        } else {
                                            ElMessage.error(response.data.message || "注册失败！");
                                        }
                                    })
                                    .catch(error => {
                                        console.error("注册错误:", error);
                                        ElMessage.error("服务器错误，请稍后再试！");
                                    });
                            } else {
                                ElMessage.error("验证码错误，请重试！");
                                this.generateCaptcha();
                            }
                        } else {
                            ElMessage.warning("请检查输入信息");
                        }
                    });
                },
                login() {
                    window.location.href = "http://localhost:8080/login.html";
                },
                // 生成随机验证码
                generateCaptcha() {
                    const canvas = document.getElementById("captchaCanvas");
                    const ctx = canvas.getContext("2d");

                    // 清空画布
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.fillStyle = "#f0f0f0";
                    ctx.fillRect(0, 0, canvas.width, canvas.height);

                    // 生成随机验证码 (4位字母+数字)
                    this.generatedCaptcha = Math.random().toString(36).substr(2, 4).toUpperCase();

                    // 设置字体样式
                    ctx.font = "20px Arial";
                    ctx.fillStyle = "#333";

                    // 添加干扰线
                    for (let i = 0; i < 3; i++) {
                        ctx.strokeStyle = this.randomColor();
                        ctx.beginPath();
                        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
                        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
                        ctx.stroke();
                    }

                    // 画验证码文本
                    for (let i = 0; i < this.generatedCaptcha.length; i++) {
                        ctx.fillStyle = this.randomColor();
                        ctx.fillText(this.generatedCaptcha[i], 20 + i * 20, 30);
                    }
                },

                // 生成随机颜色
                randomColor() {
                    let r = Math.floor(Math.random() * 256);
                    let g = Math.floor(Math.random() * 256);
                    let b = Math.floor(Math.random() * 256);
                    return `rgb(${r}, ${g}, ${b})`;
                },
            }
        }).use(ElementPlus).use(ElMessage).mount('#app');
    </script>
</body>

</html>